//
//  MKNetworking.m
//  Teleport
//
//  Created by xtjun on 2020/5/18.
//  Copyright © 2020 xxt. All rights reserved.
//

#import "TJNetworking.h"
#import "NSError+category.h"


@interface TJNetworking()

@property (strong, nonatomic) AFHTTPSessionManager *sessionManager;

@end


@implementation TJNetworking

static TJNetworking *instance = nil;

+ (instancetype)shareNetworking {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TJNetworking alloc] init];
        instance.sessionManager = [[AFHTTPSessionManager alloc] init];
        [instance.sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        instance.sessionManager.requestSerializer.timeoutInterval = 15.f;
        [instance.sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        instance.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
        ((AFJSONResponseSerializer *)instance.sessionManager.responseSerializer).removesKeysWithNullValues = YES;
        instance.sessionManager.operationQueue.maxConcurrentOperationCount = 5;
        
    });
    return instance;
}


/**post 参数不在body 里面 */
- (void)POSTNew:(NSString *)url
     parameters:(nullable id)parameters
        success:(nullable void (^)(NSDictionary *responseObject, id data))success
        failure:(nullable void (^)(NSError *error))failure {
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", baseUrlString, url];
    
    TJLog(@"pathURl =%@ ----- parameters = %@", [NSString stringWithFormat:@"%@%@", baseUrlString, url], parameters);
    
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    TJUserInfo *userInfo = [TJUserInfo readInfo];
    if (userInfo.token) [header setObject:userInfo.token forKey:@"token"];
    if (userInfo.userId) [header setObject:userInfo.userId forKey:@"userId"];
    [self.sessionManager POST:requestUrl parameters:parameters headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        TJLog(@"url-%@ responseObject = %@", url, responseObject);
        handleResponseObject(responseObject, success, failure);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        TJLog(@"%@ ----- error = %@", url, error);
        handleResponseObject(nil, nil, failure);
    }];
    
    
}

- (void)GET:(NSString *)url
     parameters:(nullable id)parameters
        success:(nullable void (^)(NSDictionary *responseObject, id data))success
        failure:(nullable void (^)(NSError *error))failure {
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", baseUrlString, url];
    
    TJLog(@"pathURl =%@ ----- parameters = %@", [NSString stringWithFormat:@"%@%@", baseUrlString, url], parameters);
    
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    TJUserInfo *userInfo = [TJUserInfo readInfo];
    if (userInfo.token) [header setObject:userInfo.token forKey:@"token"];
    if (userInfo.userId) [header setObject:userInfo.userId forKey:@"userId"];
    [self.sessionManager GET:requestUrl parameters:parameters headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        TJLog(@"url-%@ responseObject = %@", url, responseObject);
        handleResponseObject(responseObject, success, failure);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        TJLog(@"%@ ----- error = %@", url, error);
        NSURLResponse *res = [task response];
        NSHTTPURLResponse *httpRes = (NSHTTPURLResponse *)res;

        handleResponseObject(@{@"errorCode": @([httpRes statusCode]).stringValue}, nil, failure);
    }];
    
    
}



- (void)updataImageWithImage:(UIImage *)image success:(void (^)(NSDictionary * _Nonnull, id _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure {
    
    NSData *fileData = [UIImage lubanCompressImage:image];
    [self.sessionManager POST:[NSString stringWithFormat:@"%@member/member/upload", baseUrlString] parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
         [formatter setDateFormat:@"yyMMddHHmmss"];
         NSString *fileName =  [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
         
         if (formData) {
             [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:@"image/png"];
         }
         
     } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
         TJLog(@"图片上传成功 ----- responseObject = %@", responseObject);
         handleResponseObject(responseObject, success, failure);
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         TJLog(@"图片上传失败 ----- error = %@" , error);
         if (failure) failure(error);
     }];
    
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method url:(NSString *)url parameters:(id)parameters {
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:url parameters:parameters error:nil];
    [request willChangeValueForKey:@"timeoutInterval"];
    request.timeoutInterval = 10.f;
    [request didChangeValueForKey:@"timeoutInterval"];
    
    //    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    TJUserInfo *userInfo = [TJUserInfo readInfo];
    if (userInfo.token) [request setValue:userInfo.token forHTTPHeaderField:@"token"];
    if (userInfo.userId) [request setValue:userInfo.userId forHTTPHeaderField:@"id"];
    
    return request;
}

void handleResponseObject(NSDictionary *responseObject, void (^success)(NSDictionary *, id), void (^failure)(NSError *)) {
    
    if (![responseObject isKindOfClass:NSDictionary.class]) return ;
    if (!responseObject.allKeys.count) return;
    

    int code = [responseObject[@"errorCode"] intValue];
    NSString *message = responseObject[@"errorMessage"];
    
    switch (code) {
        case 401:{//需要登录 token 过期15
            if (failure) {
    
                [[NSNotificationCenter defaultCenter] postNotificationName:tokenErrorNotification object:nil];
                failure([NSError errorWithCode:code errorReason:message]);
            }
            break;
        }
            
        case 0: {//成功
            if (success) {
                success(responseObject, responseObject[@"result"]);
            }
            break;
        }
        default: {
            if (failure) {
                failure([NSError errorWithCode:code errorReason:message]);
            }
        }
            break;
    }
    
    
}

/**post 参数在body 里面 */
- (void)POST:(NSString *)url
  parameters:(nullable id)parameters
     success:(nullable void (^)(NSDictionary *responseObject, id data))success
     failure:(nullable void (^)(NSError *error))failure {
    
    
    NSMutableDictionary *MParameters = nil;
    if (parameters) {
        MParameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
        
        NSString *language = [TJGlobalFunc languageValue:TJGlobalFunc.language];
        
        [MParameters setValue:language forKey:@"lang"];
    } else {
        MParameters = @{}.mutableCopy;
    }
    TJLog(@"pathURl =%@ ----- parameters = %@", [NSString stringWithFormat:@"%@%@", baseUrlString, url], MParameters);
    
    NSMutableURLRequest *request = [self requestWithMethod:@"POST" url:[NSString stringWithFormat:@"%@%@", baseUrlString, url] parameters:MParameters.copy];
    [[self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, NSDictionary *responseObject, NSError * _Nullable error) {
        TJLog(@"url-%@ responseObject = %@", url, responseObject);
        
        if (error) {
            TJLog(@"%@ ----- error = %@", url, error);
            if (failure) {
                failure(error);
            }
            return ;
        }
        handleResponseObject(responseObject, success, failure);
    }] resume];
    
}
- (void)updataImageWithUrl:(NSString *)url
                  fileData:(NSData *)fileData
                parameters:(nullable id)parameters
                   success:(void (^)(NSDictionary *, id))success
                   failure:(void (^)(NSError *))failure {
    
    [self.sessionManager POST:[NSString stringWithFormat:@"%@%@", baseUrlString, url] parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyMMddHHmmss"];
        NSString *fileName =  [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        
        if (formData) {
            [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:@"image/png"];
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        TJLog(@"%@ ----- responseObject = %@", url, responseObject);
        handleResponseObject(responseObject, success, failure);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        TJLog(@"%@ ----- error = %@", url, error);
        if (failure) failure(error);
    }];
}

/**跟新用户信息 */
- (void)updateUserInfoAndLoading:(BOOL)isLoading success:(nullable void (^)(TJUserInfo *userInfo))success{
    if (isLoading) {
        [TJHud showloading];
    }
    //获取用户信息
    [TJNetworking.shareNetworking GET:@"member/member/getMember" parameters:@{@"userId": TJUserInfo.readInfo.userId ?: @""} success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
         [TJHud hiddenloading];
         TJUserInfo *userInfo = TJUserInfo.readInfo;
         [userInfo updateUserInfoWithInfoDict:data];
         success(userInfo);
     } failure:^(NSError * _Nonnull error) {
           [TJHud hiddenloading];
         [TJHud showAutoHideMessage:error.localizedFailureReason];
  
     }];
}

//- (void)GET:(NSString *)url
// parameters:(nullable id)parameters
//    success:(nullable void (^)(NSDictionary *responseObject, id data))success
//    failure:(nullable void (^)(NSError *error))failure {
//
//
//    NSMutableDictionary *MParameters = nil;
//    if (parameters) {
//        MParameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
//        NSString *language = [TJGlobalFunc languageValue:TJGlobalFunc.language];
//        [MParameters setValue:language forKey:@"lang"];
//    } else {
//        MParameters = @{}.mutableCopy;
//    }
//
//    TJLog(@"%@ ----- parameters = %@", [NSString stringWithFormat:@"%@%@", baseUrlString, url], parameters);
//
//    NSMutableURLRequest *request = [self requestWithMethod:@"GET" url:[NSString stringWithFormat:@"%@%@", baseUrlString, url] parameters:MParameters.copy];
//    [[self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, NSDictionary *responseObject, NSError * _Nullable error) {
//        TJLog(@"url-%@ responseObject = %@", url, responseObject);
//
//        if (error) {
//            TJLog(@"%@ ----- error = %@", url, error);
//            if (failure) {
//                failure(error);
//            }
//            return ;
//        }
//        handleResponseObject(responseObject, success, failure);
//    }] resume];
//}

@end
